﻿using System;
using System.Globalization;
using System.Net.Mail;
using System.Text;
using mvcForum.Core;
using mvcForum.Core.Abstractions.Interfaces;
using mvcForum.Core.Events;
using mvcForum.Core.Interfaces.Events;
using mvcForum.Web.Extensions;

using SimpleLocalisation;
using mvcForum.Core.Interfaces.Data;
using mvcForum.Core.Interfaces.Services;

namespace mvcForum.Web.Events {

	public class PostReportResolvedEventListener : IAsyncEventListener<PostReportResolvedEvent> {
		private readonly IAsyncTask task;
		private readonly IRepository<PostReport> prRepo;
		private readonly IConfiguration config;
		private readonly ILogger logger;
		// TODO: Exchange this with a interface!!!
		private readonly TextManager texts;

		public PostReportResolvedEventListener(IAsyncTask task, IRepository<PostReport> prRepo, IConfiguration config, ILogger logger, TextManager texts) {
			this.task = task;
			this.prRepo = prRepo;
			this.config = config;
			this.logger = logger;
			this.texts = texts;
		}

		public void Queue(PostReportResolvedEvent payload) {
			this.task.Execute(this, payload, 15);
		}

		public void Handle(Object payload) {
			if (payload is PostReportResolvedEvent) {
				this.Handle((PostReportResolvedEvent)payload);
			}
			else {
				throw new ApplicationException("Unknown payload!");
			}
		}

		public void Handle(PostReportResolvedEvent payload) {
			PostReport pr = this.prRepo.Read(payload.PostReportId);

			// Do the reporter want feedback?
			if (pr.Feedback && pr.ReportedBy != null && !String.IsNullOrWhiteSpace(pr.ReportedBy.EmailAddress)) {
				// Yes, let's give him feedback!
				String recipientEmail = pr.ReportedBy.EmailAddress;
				String recipientName = pr.ReportedBy.Name;

				MailMessage message = new MailMessage();
				// Get the "from address" and "from name" from the configuration.
				message.From = new MailAddress(this.config.RobotEmailAddress, this.config.RobotName);
				// And let's put the user's e-mail address in the to field.
				message.To.Add(new MailAddress(recipientEmail, recipientName));
				// UTF8 FTW!
				message.SubjectEncoding = Encoding.UTF8;
				message.BodyEncoding = Encoding.UTF8;

				String culture = pr.ReportedBy.Culture;
				// TODO:
				//Language userLI = new Language { Key = culture };

				message.Subject = this.texts.Get<mvcForum.Web.ForumConfigurator>("PostReportResolvedSubject", new { Post = pr.Post, Report = pr }/*, userLI*/);
				message.Body = this.texts.Get<mvcForum.Web.ForumConfigurator>("PostReportResolvedBody", new { Post = pr.Post, Report = pr }/*, userLI*/);
				message.IsBodyHtml = false;

				try {
					// Create a SMTP client, this will use the settings from the web.config file.
					SmtpClient client = new SmtpClient();
					// Send the message.
					client.Send(message);

					logger.Log(EventType.Debug, String.Format("The e-mail to user {0} ({1}) has been sent.", recipientName, recipientEmail));
				}
				catch (Exception ex) {
					logger.Log(EventType.Error, String.Format("Could not send e-mail to {0} from AsyncController, MessageAdded", recipientEmail), ex);
				}
			}
		}

		public Byte Priority {
			get {
				return (Byte)EventPriority.Lowest;
			}
		}

		public Boolean RunAsynchronously {
			get {
				return true;
			}
		}

		public Boolean UniqueEvent {
			get {
				return false;
			}
		}
	}
}